/*
 * Teknei 2014 - All rights reserved
 */
package com.teknei.acabus.core.filter;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.ejb.EJB;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.teknei.acabus.core.entities.NavigationChild;
import com.teknei.acabus.core.entities.NavigationParent;
import com.teknei.acabus.core.singleton.NavigationSingleton;

/**
 * Servlet Filter implementation class NavigationFilter.
 * Filter for set MenuModel elements when the request is based on URL
 * @version 1.0
 * @since 1.0
 * @author Jorge Amaro
 */
public class NavigationFilter implements Filter {

	@EJB
	private NavigationSingleton navigationSingleton;

	private final static Logger LOG = LoggerFactory
			.getLogger(NavigationFilter.class);

	/**
	 * Default constructor.
	 */
	public NavigationFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String refer = ((HttpServletRequest) request).getHeader("referer");
		if (refer == null) {
			String uri = ((HttpServletRequest) request).getRequestURI();
			int idexOfSlash = uri.indexOf("/", 1);
			uri = uri.substring(idexOfSlash);
			Map<NavigationParent, NavigationChild> map = navigationSingleton
					.findNavigation(uri);
			Set<NavigationParent> parents = map.keySet();
			for(NavigationParent parent : parents){
				request.setAttribute("parent", parent);
				request.setAttribute("child", map.get(parent));
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @return the navigationSingleton
	 */
	public NavigationSingleton getNavigationSingleton() {
		return navigationSingleton;
	}

	/**
	 * @param navigationSingleton the navigationSingleton to set
	 */
	public void setNavigationSingleton(NavigationSingleton navigationSingleton) {
		this.navigationSingleton = navigationSingleton;
	}

}
